package com.jstyle.blesdkota.ble2318ota_plugin;

import android.util.Log;

import java.nio.charset.StandardCharsets;

public class Utils {
    private static final int SHORTENED_LOCAL_NAME = 0x08;
    private static final int COMPLETE_LOCAL_NAME = 0x09;

    public static int getValue(byte b, int count) {
        return (int) ((b & 0xff) * Math.pow(256, count));
    }

    /**
     * Decodes the local name
     */
    public static String decodeLocalName(final byte[] data, final int start,
                                         final int length) {
        try {
            return new String(data, start, length, StandardCharsets.UTF_8);
        } catch (final IndexOutOfBoundsException e) {
            Log.e("scan", "Error when reading complete local name", e);
            return null;
        }
    }

    public static String decodeDeviceName(byte[] data) {
        String name = null;
        int fieldLength, fieldName;
        int packetLength = data.length;
        for (int index = 0; index < packetLength; index++) {
            fieldLength = getValue(data[index],0);
            if (fieldLength <= 0)
                break;
            fieldName = getValue(data[++index],0);;

            if (fieldName == COMPLETE_LOCAL_NAME
                    || fieldName == SHORTENED_LOCAL_NAME) {
                name = decodeLocalName(data, index + 1, fieldLength - 1);
                break;
            }
            index += fieldLength - 1;
        }
        return name;
    }
}
